<template>
  <div class="u-page mai-conversation-add">
    <!-- 🔼 自定义发圈 头部（导航栏） -->
    <div class="conversation_head_weichat">
      <div @click="goBack()" class="conversation_head_back_button_weichat">
        <img src="/static/icon/common/return-icon.png" />
      </div>
      <div class="conversation_head_title_weichat">发布朋友圈</div>
	  <!-- ✅ 推荐写法：将 click 写在 u-button 上 -->
	  <div class="conversation_head_send_button_weichat">
	    <u-button type="success" text="发表" @click="sendMoments" />
	  </div>
    </div>

    <!-- 🧾 文字输入与图片选择区域 -->
    <div class="bg_send_moments">
      <div class="send_msg">
        <u-textarea v-model="send_msg" placeholder="请输入内容" border="bottom" />
      </div>
      <div class="send_photo">
        <uni-file-picker
          v-model="momentsImg"
          file-mediatype="image"
          mode="grid"
          file-extname="png,jpg"
          :limit="9"
          @progress="progress"
          @success="success"
          @fail="fail"
          @select="select"
        />
      </div>
    </div>

    <!-- 📍 所在位置（未启用） -->
    <div class="show_item">
      <div class="show_item_icon"><img src="/static/icon/moments/position.png" /></div>
      <div class="show_item_text">所在位置</div>
      <div class="show_itme_arrow"><u-icon name="arrow-right" color="#ddd" size="22" /></div>
    </div>

    <!-- 👥 提醒谁看（未启用） -->
    <div class="show_item">
      <div class="show_item_icon"><img src="/static/icon/moments/at.png" /></div>
      <div class="show_item_text">提醒谁看</div>
      <div class="show_itme_arrow"><u-icon name="arrow-right" color="#ddd" size="22" /></div>
    </div>

    <!-- 🔓 谁可以看 -->
    <div class="show_item">
      <div class="show_item_icon"><img src="/static/icon/moments/man.png" /></div>
      <div class="show_item_text">谁可以看</div>
      <div class="action_text">公开</div>
      <div class="show_itme_arrow"><u-icon name="arrow-right" color="#ddd" size="22" /></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from '/TUIKit/adapter-vue'
import { postMoment } from '@/api/moments'

const send_msg = ref('')
const momentsImg = ref([])                // UI 显示用
const momentsImgUrl = ref<string[]>([])  // 真正上传成功后的 URL 列表
const uploading = ref(false)             // 图片上传状态

// 进度回调
const progress = (option) => {
  console.log('上传进度：', option)
}

// 上传失败
const fail = (option) => {
  console.error('上传失败：', option)
}

// 上传成功
const success = (option) => {
  console.error('上传成功：', option)
}

// ✅ 多图上传逻辑
const select = async (option) => {
  const filePaths = option.tempFilePaths
  if (!filePaths || filePaths.length === 0) {
    uni.showToast({ title: '未选择图片', icon: 'none' })
    return
  }

  const baseUrl = uni.$baseUrl
  const baseImgUrl = uni.$baseImgUrl
  const token = uni.getStorageSync('token')

  uploading.value = true // 开始上传

  for (const filePath of filePaths) {
    await new Promise<void>((resolve) => {
      uni.uploadFile({
        url: `${baseUrl}/home/user/uploads`,
        filePath,
        name: 'file',
        header: { 'X-Csrf-Token': token },
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            if (data.code === 200) {
              const imageUrl = baseImgUrl + data.data
              momentsImgUrl.value.push(imageUrl)
              console.log('上传成功：', imageUrl)
            } else {
              uni.showToast({ title: data.msg || '上传失败', icon: 'none' })
            }
          } catch (e) {
            console.error('解析失败', e)
            uni.showToast({ title: '响应异常', icon: 'none' })
          }
          resolve()
        },
        fail: (err) => {
          console.error('上传失败：', err)
          uni.showToast({ title: '上传失败', icon: 'none' })
          resolve()
        }
      })
    })
  }

  uploading.value = false // 全部上传结束
}

// ✅ 发送朋友圈
const sendMoments = async () => {
  if (uploading.value) {
    uni.showToast({ title: '图片上传中，请稍后', icon: 'none' })
    return
  }

  if (!send_msg.value && momentsImgUrl.value.length === 0) {
    uni.showToast({ title: '请输入内容或选择图片', icon: 'none' })
    return
  }

  try {
    const res = await postMoment({
      user_id: uni.getStorageSync('userAppInfo').id,
      content: send_msg.value,
      images: momentsImgUrl.value,
      privacy: 0
    })

    if (res.data.code === 200) {
	  uni.showToast({ title: '发布成功', icon: 'success' })
	  uni.$emit('refreshMomentList')   // ✅ 关键代码
	  uni.navigateBack()
    } else {
      uni.showToast({ title: res.msg || '发布失败', icon: 'none' })
    }
  } catch (e) {
    console.error('接口异常：', e)
    uni.showToast({ title: '网络错误', icon: 'none' })
  }
}

// 返回
const goBack = () => {
  uni.navigateBack()
}
</script>


<style>
.mai-conversation-add {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: #f9f9f9;
  overflow: hidden;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, sans-serif;
}

/* 顶部栏样式 */
.conversation_head_weichat {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: env(safe-area-inset-top) 12px 0 12px;
  height: calc(44px + env(safe-area-inset-top));
  background-color: #f5f5f5;
  border-bottom: 1px solid #e5e5e5;
}
.conversation_head_back_button_weichat img {
  width: 24px;
  height: 24px;
}
.conversation_head_back_button_weichat,
.conversation_head_send_button_weichat {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
}
.conversation_head_title_weichat {
  font-size: 16px;
  font-weight: 600;
  flex: 1;
  text-align: center;
  line-height: 44px;
  color: #222;
}

/* 输入框、图片选择 */
.bg_send_moments {
  padding: 16px;
  background-color: #fff;
  margin-bottom: 12px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.send_msg {
  height: 120px;
}
.send_photo {
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

/* 下方选项样式 */
.show_item {
  display: flex;
  align-items: center;
  height: 52px;
  background-color: #fff;
  padding: 0 12px;
  border-top: 1px solid #f2f2f2;
  border-bottom: 1px solid #f2f2f2;
}
.show_item_icon {
  margin-right: 12px;
}
.show_item_icon img {
  width: 22px;
  height: 22px;
}
.show_item_text {
  flex: 1;
  font-size: 15px;
  color: #333;
}
.action_text {
  font-size: 14px;
  color: #999;
  margin-right: 8px;
}
.show_itme_arrow {
  margin-left: auto;
}
</style>
